(function() {

  'use strict';

  /**
   * @ngdoc function
   * @name componentsApp.controller:MainCtrl
   * @description
   * # MainCtrl
   * Controller of the sasApp
   */
  angular.module('sasApp.controllers', [
      'controllers.login', //登录
      'controllers.omdisplay', //
      'controllers.faultLocation', //故障定位模块
      'controllers.userManager', //系统管理
      'controllers.timeDataDis', //动态实时数据
      'controllers.sysServiceData', //
      'controllers.resourcesWatchData', //
      'controllers.oldOMDisplay', //老需求
      'controllers.customActivity', //
      'controllers.pbossSysBusiness', //
      'controllers.analysisSysOM',
      'controllers.dataManager', //数据管理
      //'controllers.alarmStatisticsAnalysis',
      'controllers.workOrderData',
      'controllers.alarmDataAnalysis', //告警数据分析
      'controllers.userBehaviorAnalysis' //用户行为指标分析
    ])
    .controller('mainController', function($rootScope, $scope, $mdSidenav, $cookies, BusinessLine, System, CoreService, COREDATA, Provinces, $state, $timeout, LoginServer, Restangular, customizationService, SystemModulesService, CoreServer) {
      $rootScope.roleInfo = SystemModulesService._modules;
      //角色信息
      var roleCookie = {
        loginUser: $rootScope.roleInfo.loginUser,
        userId: $rootScope.roleInfo.roleId,
        roleName: $rootScope.roleInfo.roleName,
        staffName: $rootScope.roleInfo.staffName
      };
      $cookies.putObject('userCookie', roleCookie);
      // checkUserState();
      //用户de姓名
      $scope.realName = roleCookie.loginUser;
      //省份Provinces,排序后
      COREDATA.PROVINCES = CoreService.sort(Provinces, 'provinceCode');
      //业务线
      COREDATA.BUSINESSLINE = BusinessLine;
      //业务系统
      COREDATA.SYSTEM = System;
      //=========导航栏样式=======开始
      $scope.isActive = {
        span1: true,
        span2: false,
        span3: false,
        span4: false,
        span5: false,
        span6: false,
        span7: false,
        span8: false
      };
      $scope.pageItmes = [10, 20, 50, 100];
      var spans = ['span1', 'span2', 'span3', 'span4', 'span5', 'span6', 'span7', 'span8'];
      /**
       * [navgit 导航条样式修复] function
       * @param  {[array]} span [所有的tab]
       */
      $scope.navgit = function(span) {

        for (var p in $scope.isActive) {
          if ($scope.isActive.hasOwnProperty(p)) {
            $scope.isActive[p] = p === span;
          }
        }
      };
      $scope.$on('$stateChangeSuccess', function(evt, state) {
        var moduleName = state.name.split('.')[1];
        switch (moduleName) {
          case 'omdisplay':
            $scope.navgit(spans[0]);
            break;
          case 'timeDataDis':
            $scope.navgit(spans[1]);
            break;
          case 'activity':
            $scope.navgit(spans[2]);
            break;
          case 'realTimeDisplay':
            $scope.navgit(spans[2]);
            break;
          case 'realTimeActivity':
            $scope.navgit(spans[2]);
            break;
          case 'display':
            $scope.navgit(spans[2]);
            break;
          case 'activityEdit':
            $scope.navgit(spans[2]);
            break;
          case 'summaryActivityEdit':
            $scope.navgit(spans[2]);
            break;
          case 'summary':
            $scope.navgit(spans[2]);
            break;
          case 'analysisSysOM':
            $scope.navgit(spans[3]);
            break;
          case 'dataQualityMng':
            $scope.navgit(spans[4]);
            break;
          case 'alarmDataAnalysis':
            $scope.navgit(spans[5]);
            break;
          case 'workOrderData':
            $scope.navgit(spans[6]);
            break;
          case 'userBehaviorAnalysis':
            $scope.navgit(spans[7]);
            break;
          default:
            $scope.navgit(false);
        }
      });

      //初始化显示该用户下的模块
      $rootScope.module = customizationService.initGetModules();
      $scope.queryModules = function() {
        var myParam = {
          userId: $cookies.getObject('userCookie').userId
        };
        customizationService.queryUserModule(myParam, function(res) {
          $scope.userModules = res.data;
        });
      };

      $scope.$watch('module.userModules', function(newValue, oldValue) {
        var userIds = [];
        var am = [];
        angular.forEach($rootScope.module.modules, function(n) {
          am.push(n.moduleId);
          if (n.childModule.length >= 1) {
            angular.forEach(n.childModule, function(nc) {
              am.push(nc.moduleId);
            })
          }
        })
        for (var nv in newValue) {
          if (newValue[nv].length > 1) {
            angular.forEach(newValue[nv], function(n) {
              userIds.push(n);
            })
          }

        }
        angular.forEach(am, function(ids) {
          var mds = $rootScope.roleInfo.moduleIds;
          if (mds.indexOf(ids) !== -1) {
            $rootScope.roleInfo.moduleIds.splice(mds.indexOf(ids), 1);
          }
        })
        $rootScope.roleInfo.moduleIds = userIds.concat($rootScope.roleInfo.moduleIds);
        $scope.queryModules();
      }, true);
      //无用库表作业清理和个人页面定制区分字段
      $rootScope.customizationTitle = '';
      /**
       * [logout 退出登陆] function
       */
      $scope.logout = function() {
        if (confirm('确认退出吗')) {
          CoreServer.logOut(function(res) {
            if (res.result === 0) {
              window.location.href = res.data;
            } else {
              CoreService.dialog('退出失败');
            }
          })
        }
        // LoginServer.signOut( {userId:$cookies.getObject('userCookie').userId} );
      };

      /**
       * [checkUserState 判断用户是否登陆] function
       */
      function checkUserState() {
        if ($cookies.getObject('userCookie') === undefined) {
          $state.go('login');
        } else {
          COREDATA.USERINFO.REALNAME = $cookies.getObject('userCookie').realName;
        }
      }
      /**
       * function [_getNames] 获取下拉框要显示de文字
       * @param  {Array} series         [下拉框数组对象]
       * @param  {String} propertyName  [数组中的属性字符]
       * @param  {Object} objArr        [需要比较的最大的数组对象]
       * @public
       */
      $scope._getNames = function(series, propertyName, objArr) {
        if (angular.isArray(series)) {
          if (series.length === objArr.length || series.length === 0) {
            return '全部';
          }
          var arrName = series.map(function(item) {
            if (!item) {
              return undefined;
            }
            return item[propertyName];
          });
          return arrName.join(',');
        } else {
          return series[propertyName];
        }
      };

      /**
       * function [_checkAll]  下拉框全选
       *
       * @param series           [下拉框数组对象]
       * @param propertyName     [数组中的属性字符]
       * @public
       */
      $scope._checkAll = function(series, propertyName) {
        $timeout(function() {
          series[propertyName] = [];
        });
      };

      //页面等待效果(转转转)
      $rootScope._loading = CoreService._loading;

      //若服务器端session过期返回10009错误,则退出登录
      Restangular.addResponseInterceptor(function(data) {
        if (data.state === '10009') {
          $cookies.remove('userCookie');
          $state.go('login');
          CoreService.dialog(data.state);
          // $scope.logout();
        } else {
          return data;
        }
      });
      /* 主页搜索 点击圆形按钮弹出搜索框 可以拖动按钮到页面的任何位置*/
      $scope.obj = {
        simulateQuery: false,
        querySearch: querySearch
      };
      //跳转
      $scope.jumpPage = function(text) {
        var t = text.trim();
        angular.forEach($scope.userModules, function(item) {
          if (item.moduleName === t) {
            $state.go(item.url);
            $scope.close();
          }
        });
      };
      //查询
      function querySearch(queryText) {
        return queryText ? filterText(queryText) : $scope.userModules;
      }
      //过滤
      function filterText(text) {
        var selectArr = [];
        angular.forEach($scope.userModules, function(item) {
          if (item.moduleName.indexOf(text) !== -1) {
            selectArr.push(item);
          }
        });
        return selectArr;
      }
      /* 弹出框关闭事件 */
      $scope.close = function() {
        $('.modal_btn').css('display', 'none');
      }

      /* 鼠标拖动事件 */
      var sftd = true;
      $('#menu_').mousedown(function(e) { //鼠标按下事件
        $(this).css('cursor', 'move'); //改变鼠标指针的形状
        // sftd = true;
        var offset = $(this).offset(); //BUTTON在页面的位置
        var x = e.pageX - offset.left; //获得鼠标指针离BUTTON元素左边界的距离
        var y = e.pageY - offset.top; //获得鼠标指针离BUTTON元素上边界的距离
        $timeout(function() {
          $(document).bind('mousemove', function(ev) { //绑定鼠标的移动事件，因为光标在BUTTON元素外面也要有效果，所以要用doucment的事件，而不用BUTTON元素的事件
            var clientWidth = document.body.clientWidth; //浏览器宽度
            var clientHeight = document.body.clientHeight - 30; //浏览器高度
            var divWidth = $('.modal_btn').width(); //弹出框div宽度
            var divHeight = $('.modal_btn').height(); //弹出框div高度
            var btnWidth = $('#menu_').width(); //点击按钮宽度
            var btnHeight = $('#menu_').height(); //点击按钮高度

            $('#menu_').stop(); //按钮停止移动
            var _x = ev.pageX - x; //获得X轴方向移动的值
            var _y = ev.pageY - y; //获得Y轴方向移动的值
            //判断拖动按钮离页面上下左右四个面的距离,防止按钮拖出页面外
            if (ev.pageX - x <= 0) {
              _x = 0;
            }
            if (ev.pageY - y <= 0) {
              _y = 0;
            }
            if (ev.pageX - x >= (clientWidth - btnWidth)) {
              _x = clientWidth - btnWidth;
            }
            if (ev.pageY - y >= (clientHeight - btnHeight)) {
              _y = clientHeight - btnHeight;
            }

            var height_ = _y + btnHeight + divHeight;
            var width_ = _x + btnWidth + divWidth;
            $('#menu_').animate({
              left: _x + 'px',
              top: _y + 'px'
            }, 0);
            //判断弹出框出现的位置
            if (height_ > clientHeight && width_ < clientWidth) {
              $('.modal_btn').animate({
                left: _x + btnWidth + 'px',
                top: _y - divHeight + 'px'
              }, 0);
            } else if (height_ > clientHeight && width_ > clientWidth) {
              $('.modal_btn').animate({
                left: _x - divWidth + 'px',
                top: _y - divHeight + 'px'
              }, 0);
            } else if (width_ > clientWidth) {
              $('.modal_btn').animate({
                left: _x - divWidth + 'px',
                top: _y + btnHeight + 'px'
              }, 0);
            } else {
              $('.modal_btn').animate({
                left: _x + btnWidth + 'px',
                top: _y + btnHeight + 'px'
              }, 0);
            }
            sftd = false;
          });
        }, 50)
      });
      /* 拖动按钮点击事件 */
      $('#menu_').click(function() {
        sftd = !sftd;
        if (sftd) {
          $('.modal_btn').css('display', 'none');
        } else {
          $('.modal_btn').css('display', 'block');
        }
      });
      /* 鼠标松开事件 */
      $(document).mouseup(function(e) {
        $('#menu_').css('cursor', 'pointer');
        $(this).unbind('mousemove');
        e.stopPropagation();
      });
      // 顶部导航滑动
      $scope.scrollTabs = function(direction) {
        $('#scrollTabs').animate({
          scrollLeft: $('#scrollTabs').scrollLeft() + 144 * (direction == 'right' ? 1 : -1)
        }, 100);
      }
    });

})();